<template>
  <div class="order-list-page">
    <!-- 筛选入口 -->
    <div class="filter-bar">
      <div class="filter-info">
        <div class="filter-title">订单筛选</div>
        <div class="filter-desc">{{ filterSummaryText }}</div>
      </div>
      <nut-button size="small" type="primary" plain @click="openFilter">筛选</nut-button>
    </div>

    <!-- 订单列表 -->
    <nut-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <div v-if="orderList.length === 0 && !loading" class="empty-state">
        <nut-empty description="暂无订单数据" />
      </div>
      <div v-else class="order-list">
        <nut-cell-group
          v-for="item in orderList"
          :key="item.orderId"
          class="order-item"
          @click="goToDetail(item.orderId)"
        >
          <nut-cell>
            <template #desc>
              <div class="order-content">
                <!-- 顶部：产品名称 + 订单状态 -->
                <div class="order-header">
                  <div class="product-name">{{ item.productName || '--' }}</div>
                  <div class="order-status" :class="`status-${item.orderStatus || 'default'}`">
                    {{ getOrderStatusText(item.orderStatus) || '--' }}
                  </div>
                </div>
                <!-- 客户信息 -->
                <div class="order-info-item">
                  <span class="label">客户姓名:</span>
                  <span class="value">{{ item.customName || '--' }}</span>
                </div>
                <div class="order-info-item">
                  <span class="label">证件号码:</span>
                  <span class="value">{{ item.customIdCard || '--' }}</span>
                </div>
                <div class="order-info-item">
                  <span class="label">客户手机号:</span>
                  <span class="value">{{ item.customPhone || '--' }}</span>
                </div>
                <div class="order-info-item">
                  <span class="label">订单时间:</span>
                  <span class="value">{{ formatTime(item.orderTime) }}</span>
                </div>
                <div class="order-info-item">
                  <span class="label">补录状态:</span>
                  <span class="value">{{ getSupplementStatusText(item.supplementStatus) }}</span>
                </div>
                <!-- 操作按钮 -->
                <div class="order-actions">
                  <nut-button
                    v-if="item.supplementStatus !== '01'"
                    size="small"
                    type="primary"
                    @click.stop="goToSupplement(item.orderId)"
                  >
                    补录订单
                  </nut-button>
                  <nut-button
                    v-if="item.supplementStatus === '01'"
                    size="small"
                    type="primary"
                    @click.stop="goToUpdate(item.orderId)"
                  >
                    修改订单
                  </nut-button>
                </div>
              </div>
            </template>
          </nut-cell>
        </nut-cell-group>
        <!-- 加载更多提示 -->
        <div v-if="loading" class="loading-more"> 加载中... </div>
        <div v-else-if="!hasMore && orderList.length > 0" class="no-more"> 没有更多了 </div>
        <!-- 滚动触底元素 -->
        <div ref="loadMoreTrigger" class="load-more-trigger"></div>
      </div>
    </nut-pull-refresh>

    <!-- 筛选弹窗 -->
    <nut-popup v-model:visible="filterVisible" position="bottom" round>
      <div class="filter-popup">
        <div class="filter-popup-header">筛选条件</div>
        <nut-cell-group>
          <nut-cell title="产品">
            <template #desc>
              <span class="filter-clickable" @click="openProductPicker">
                {{ selectedProductName || '全部产品' }}
              </span>
            </template>
          </nut-cell>
          <nut-cell title="客户姓名">
            <nut-input v-model="filterForm.customName" placeholder="请输入客户姓名" clearable />
          </nut-cell>
          <nut-cell title="手机号">
            <nut-input v-model="filterForm.customPhone" placeholder="请输入客户手机号" type="tel" clearable />
          </nut-cell>
          <nut-cell title="下单开始时间">
            <nut-input
              v-model="filterForm.orderStartTime"
              placeholder="请选择下单开始时间"
              readonly
              @click="openStartTimePicker"
            />
          </nut-cell>
          <nut-cell title="下单结束时间">
            <nut-input
              v-model="filterForm.orderEndTime"
              placeholder="请选择下单结束时间"
              readonly
              @click="openEndTimePicker"
            />
          </nut-cell>
          <nut-cell title="订单状态">
            <nut-radio-group v-model="filterForm.orderStatus" direction="horizontal">
              <nut-radio label="">全部</nut-radio>
              <nut-radio
                v-for="item in orderStatusOptions"
                :key="item.dictValue || ''"
                :label="item.dictValue || ''"
              >
                {{ item.dictLabel }}
              </nut-radio>
            </nut-radio-group>
          </nut-cell>
        </nut-cell-group>

        <div class="filter-actions">
          <nut-button type="default" block @click="handleReset">重置</nut-button>
          <nut-button type="primary" block @click="handleQuery">查询</nut-button>
        </div>
      </div>
    </nut-popup>

    <!-- 产品选择器 -->
    <nut-popup v-model:visible="showProductPicker" position="bottom">
      <nut-picker
        v-model="selectedProductIndex"
        :columns="productColumns"
        title="选择产品"
        @confirm="onProductConfirm"
        @cancel="showProductPicker = false"
      />
    </nut-popup>

    <!-- 下单开始时间选择 -->
    <nut-popup v-model:visible="startTimePickerVisible" position="bottom">
      <nut-date-picker
        v-model="startTimePickerValue"
        type="date"
        :min-date="minDate"
        :max-date="maxDate"
        :three-dimensional="false"
        @confirm="onStartTimeConfirm"
        @cancel="startTimePickerVisible = false"
      />
    </nut-popup>

    <!-- 下单结束时间选择 -->
    <nut-popup v-model:visible="endTimePickerVisible" position="bottom">
      <nut-date-picker
        v-model="endTimePickerValue"
        type="date"
        :min-date="minDate"
        :max-date="maxDate"
        :three-dimensional="false"
        @confirm="onEndTimeConfirm"
        @cancel="endTimePickerVisible = false"
      />
    </nut-popup>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, reactive, computed } from 'vue';
  import { useRouter } from 'vue-router';
  import { fetchOrderList, fetchProductSelect, type OrderListItem, type ProductInfo } from '@/api/order';
  import { showToast } from '@nutui/nutui';
  import dayjs from 'dayjs';
  import { useIntersectionObserver } from '@vueuse/core';
  import { useEnumStore } from '@/store/modules/enum';

  const router = useRouter();
  const enumStore = useEnumStore();

  // 订单列表数据
  const orderList = ref<OrderListItem[]>([]);
  const loading = ref(false);
  const refreshing = ref(false);
  const hasMore = ref(true);
  const pageNum = ref(1);
  const pageSize = ref(10);
  const loadMoreTrigger = ref<HTMLElement | null>(null);

  // 日期选择相关
  const minDate = new Date(2000, 0, 1);
  const maxDate = new Date(2100, 11, 31);
  const startTimePickerVisible = ref(false);
  const startTimePickerValue = ref<Date | null>(null);
  const endTimePickerVisible = ref(false);
  const endTimePickerValue = ref<Date | null>(null);

  const formatDate = (date: Date | null) => {
    if (!date) return '';
    const y = date.getFullYear();
    const m = String(date.getMonth() + 1).padStart(2, '0');
    const d = String(date.getDate()).padStart(2, '0');
    return `${y}-${m}-${d}`;
  };

  // 获取默认日期范围（最近一周）
  const getDefaultDateRange = () => {
    const today = new Date();
    const weekAgo = new Date();
    weekAgo.setDate(today.getDate() - 7);
    return {
      startTime: formatDate(weekAgo),
      endTime: formatDate(today),
    };
  };

  const defaultDateRange = getDefaultDateRange();

  // 筛选条件
  const filterVisible = ref(false);
  const filterForm = reactive<{
    productId: string;
    customName: string;
    customPhone: string;
    orderStartTime: string;
    orderEndTime: string;
    orderStatus: string;
    supplementStatus: string;
  }>({
    productId: '',
    customName: '',
    customPhone: '',
    orderStartTime: defaultDateRange.startTime, // 默认一周前
    orderEndTime: defaultDateRange.endTime, // 默认今天
    orderStatus: '',
    supplementStatus: '',
  });

  // 产品列表（用于筛选）
  const productList = ref<ProductInfo[]>([]);
  const selectedProductName = ref('');
  const selectedProductIndex = ref<number[]>([0]);
  const showProductPicker = ref(false);

  // 枚举选项
  const orderStatusOptions = computed(() => enumStore.getEnumByType('sp_order_status'));
  const supplementStatusOptions = computed(() => enumStore.getEnumByType('supplement_status'));

  const productColumns = computed(() => [
    productList.value.map((item) => ({
      text: item.productName || '',
      value: item.productId || '',
    })),
  ]);

  const getProductList = async () => {
    try {
      const list = await fetchProductSelect();
      productList.value = list || [];
    } catch (error: any) {
      console.error('获取产品列表失败', error);
      showToast.text(error?.message || '获取产品列表失败');
    }
  };

  const openFilter = async () => {
    filterVisible.value = true;
    if (!productList.value.length) {
      await getProductList();
    }
  };

  const openProductPicker = async () => {
    if (!productList.value.length) {
      await getProductList();
    }
    showProductPicker.value = true;
  };

  const onProductConfirm = ({ selectedOptions }: any) => {
    if (selectedOptions && selectedOptions.length > 0) {
      const productId = selectedOptions[0].value as string;
      const product = productList.value.find((item) => item.productId === productId);
      filterForm.productId = productId;
      selectedProductName.value = product?.productName || '';
      const index = productList.value.findIndex((item) => item.productId === productId);
      selectedProductIndex.value = [index >= 0 ? index : 0];
      showProductPicker.value = false;
    }
  };

  const getOrderStatusText = (status?: string) => {
    if (!status) return '';
    const list = enumStore.getEnumByType('sp_order_status');
    const item = list.find((i) => i.dictValue === status);
    return item?.dictLabel || '';
  };

  const filterSummaryText = computed(() => {
    const parts: string[] = [];
    if (selectedProductName.value) {
      parts.push(selectedProductName.value);
    }
    if (filterForm.customName) {
      parts.push(`客户：${filterForm.customName}`);
    }
    if (filterForm.customPhone) {
      parts.push(filterForm.customPhone);
    }
    if (filterForm.orderStartTime) {
      parts.push(`开始：${filterForm.orderStartTime}`);
    }
    if (filterForm.orderEndTime) {
      parts.push(`结束：${filterForm.orderEndTime}`);
    }
    if (filterForm.orderStatus) {
      parts.push(getOrderStatusText(filterForm.orderStatus) || '');
    }
    if (filterForm.supplementStatus) {
      parts.push(getSupplementStatusText(filterForm.supplementStatus));
    }
    return parts.length ? parts.join('，') : '全部订单';
  });

  // 获取订单列表
  const getOrderList = async (isRefresh = false) => {
    if (loading.value) return;

    try {
      loading.value = true;
      if (isRefresh) {
        pageNum.value = 1;
        orderList.value = [];
        hasMore.value = true;
      }

      const params: Record<string, any> = {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
      };

      if (filterForm.productId) {
        params.productId = filterForm.productId;
      }
      if (filterForm.customName) {
        params.customName = filterForm.customName;
      }
      if (filterForm.customPhone) {
        params.customPhone = filterForm.customPhone;
      }
      if (filterForm.orderStartTime) {
        params.startTime = filterForm.orderStartTime;
      }
      if (filterForm.orderEndTime) {
        params.endTime = filterForm.orderEndTime;
      }
      if (filterForm.orderStatus) {
        params.orderStatus = filterForm.orderStatus;
      }
      if (filterForm.supplementStatus) {
        params.supplementStatus = filterForm.supplementStatus;
      }

      const { code, rows, msg, total }: any = await fetchOrderList(params);
      if (code !== 200) {
        showToast.text(msg || '获取订单列表失败');
        return;
      }
      orderList.value = isRefresh ? rows || [] : [...orderList.value, ...(rows || [])];
      hasMore.value = (rows?.length || 0) >= pageSize.value && orderList.value.length < (total || 0);
      if (hasMore.value) {
        pageNum.value += 1;
      }
    } catch (error: any) {
      console.error('获取订单列表失败', error);
      showToast.text(error?.message || '获取订单列表失败');
    } finally {
      loading.value = false;
      refreshing.value = false;
    }
  };

  // 下拉刷新
  const onRefresh = () => {
    refreshing.value = true;
    getOrderList(true);
  };

  // 上拉加载
  const loadMore = () => {
    if (!hasMore.value || loading.value) return;
    getOrderList();
  };

  // 打开开始时间选择器
  const openStartTimePicker = () => {
    startTimePickerValue.value = filterForm.orderStartTime ? new Date(filterForm.orderStartTime) : null;
    startTimePickerVisible.value = true;
  };

  // 开始时间选择确认
  const onStartTimeConfirm = ({ selectedValue }: any) => {
      filterForm.orderStartTime = formatDate(startTimePickerValue.value);
    startTimePickerVisible.value = false;
  };

  // 打开结束时间选择器
  const openEndTimePicker = () => {
    endTimePickerValue.value = filterForm.orderEndTime ? new Date(filterForm.orderEndTime) : null;
    endTimePickerVisible.value = true;
  };

  // 结束时间选择确认
  const onEndTimeConfirm = ({ selectedValue }: any) => {
    filterForm.orderEndTime = formatDate(endTimePickerValue.value);
    endTimePickerVisible.value = false;
  };

  // 重置筛选
  const handleReset = () => {
    filterForm.productId = '';
    filterForm.customName = '';
    filterForm.customPhone = '';
    filterForm.orderStartTime = defaultDateRange.startTime; // 重置为默认值（一周前）
    filterForm.orderEndTime = defaultDateRange.endTime; // 重置为默认值（今天）
    filterForm.orderStatus = '';
    filterForm.supplementStatus = '';
    selectedProductName.value = '';
    selectedProductIndex.value = [0];
  };

  // 查询
  const handleQuery = () => {
    filterVisible.value = false;
    getOrderList(true);
  };

  // 获取状态标签类型
  const getStatusTagType = (status?: string) => {
    switch (status) {
      case '00':
        return 'warning';
      case '01':
        return 'success';
      case '02':
        return 'danger';
      default:
        return 'default';
    }
  };

  // 获取补录状态文本（从枚举中取）
  const getSupplementStatusText = (status?: string) => {
    if (!status) return '';
    const list = enumStore.getEnumByType('supplement_status');
    const item = list.find((i) => i.dictValue === status);
    return item?.dictLabel || '';
  };

  // 格式化时间
  const formatTime = (time?: string) => {
    if (!time) return '--';
    return dayjs(time).format('YYYY-MM-DD HH:mm:ss');
  };

  // 跳转到创建订单页
  const goToCreate = () => {
    router.push('/order/create');
  };

  // 跳转到补录页
  const goToSupplement = (orderId?: string) => {
    if (!orderId) return;
    router.push({
      path: '/order/supplement',
      query: { orderId },
    });
  };

  // 跳转到修改订单页
  const goToUpdate = (orderId?: string) => {
    if (!orderId) return;
    router.push({
      path: '/order/update',
      query: { orderId },
    });
  };

  // 跳转到订单详情页
  const goToDetail = (orderId?: string) => {
    if (!orderId) return;
    router.push({
      path: '/order/detail',
      query: { orderId },
    });
  };

  // 使用 IntersectionObserver 监听滚动到底部
  useIntersectionObserver(
    loadMoreTrigger,
    (entries) => {
      const entry = entries[0];
      if (entry?.isIntersecting && hasMore.value && !loading.value) {
        loadMore();
      }
    },
    {
      threshold: 0.1,
    },
  );

  // 初始化
  onMounted(() => {
    getOrderList(true);
  });
</script>

<style lang="scss" scoped>
  .order-list-page {
    min-height: 100vh;
    // background-color: #f5f5f5;
    padding-bottom: 20px;
  }

  .create-order-btn-wrap {
    padding: 20px;
    // background-color: #fff;
    margin-bottom: 10px;
  }

  .filter-bar {
    background-color: #fff;
    margin-bottom: 10px;
    padding: 12px 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .filter-info {
      display: flex;
      flex-direction: column;
      gap: 4px;

      .filter-title {
        font-size: 28px;
        font-weight: 600;
        color: #333;
      }

      .filter-desc {
        font-size: 22px;
        color: #999;
      }
    }
  }

  .order-list {
    .order-item {
      margin-bottom: 10px;
      background-color: #fff;
      border-radius: 8px;
      overflow: hidden;

      .order-content {
        .order-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;
          padding-bottom: 12px;

          .product-name {
            font-size: 28px;
            font-weight: 600;
            color: #333;
            // flex: 1;
          }

          .order-status {
            font-size: 24px;
            padding: 4px 12px;
            border-radius: 4px;
            white-space: nowrap;

            &.status-00 {
              // 待支付
              color: #ff9500;
              background-color: #fff7ed;
            }

            &.status-01 {
              // 支付成功
              color: #07c160;
              background-color: #f0f9ff;
            }

            &.status-02 {
              // 已取消
              color: #ff3b30;
              background-color: #fff5f5;
            }

            &.status-default {
              color: #666;
              background-color: #f5f5f5;
            }
          }
        }

        .order-info-item {
          display: flex;
          margin-bottom: 8px;
          font-size: 24px;

          .label {
            color: #666;
            margin-right: 10px;
            min-width: 140px;
          }

          .value {
            color: #333;
            flex: 1;
          }
        }

        .order-actions {
          margin-top: 8px;
        }
      }
    }
  }

  .empty-state {
    padding: 100px 20px;
    text-align: center;
  }

  .loading-more,
  .no-more {
    padding: 20px;
    text-align: center;
    font-size: 24px;
    color: #999;
  }

  .load-more-trigger {
    height: 1px;
  }

  .filter-popup {
    padding: 16px 16px 24px;

    .filter-popup-header {
      font-size: 28px;
      font-weight: 600;
      margin-bottom: 12px;
      text-align: center;
    }

    .filter-actions {
      margin-top: 16px;
      display: flex;
      gap: 12px;

      .nut-button {
        flex: 1;
      }
    }

    .filter-clickable {
      color: #1989fa;
    }
  }
</style>
